<!--skaks-->
<template>
  <div class="profile-main">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>尊敬的会员</span>
          <el-button type="primary" size="mini" style="float: right">购买</el-button>
        </div>
      </template>
      <div>
        <div class="profile-summary">
          <el-row>
            <el-col :span="8">现金：￥{{ userInfo.money }}</el-col>
            <el-col :span="8">积分：{{ userInfo.points }}</el-col>
            <el-col :span="8">优惠券：{{ coupons.length }}</el-col>
          </el-row>
        </div>
        <el-divider></el-divider>
        <div class="order-status">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="全部订单" name="all">
              <div v-if="orders.all.length || orders.hotel.all.length">
                <div v-for="order in orders.all" :key="order.id" class="order-item">
                  <p>订单号: {{ order.orderNo }}</p>
                  <p>航班ID: {{ order.flightID }}</p>
                  <p>价格: {{ order.price }}</p>
                  <p>舱位类型: {{ order.spaceType }}</p>
                  <p>总价: {{ order.tprice }}</p>
                  <p>购买数量: {{ order.buyNum }}</p>
                  <p>订单时间: {{ order.orderTime }}</p>
                </div>
                <div v-for="order in orders.hotel.all" :key="order.id" class="order-item">
                  <p>订单号: {{ order.id }}</p>
                  <p>酒店ID: {{ order.hotelID }}</p>
                  <p>房间号: {{ order.roomNum }}</p>
                  <p>房间类型: {{ order.roomType }}</p>
                  <p>入住时间: {{ order.rztime }}</p>
                  <p>退房时间: {{ order.tftime }}</p>
                  <p>支付方式: {{ order.payWay }}</p>
                  <p>价格: {{ order.price }}</p>
                </div>
              </div>
              <div v-else class="no-data">暂时没有相关订单</div>
            </el-tab-pane>
            <el-tab-pane label="未出行" name="upcoming">
              <div v-if="orders.upcoming.length || orders.hotel.upcoming.length">
                <div v-for="order in orders.upcoming" :key="order.id" class="order-item">
                  <p>订单号: {{ order.orderNo }}</p>
                  <p>航班ID: {{ order.flightID }}</p>
                  <p>价格: {{ order.price }}</p>
                  <p>舱位类型: {{ order.spaceType }}</p>
                  <p>总价: {{ order.tprice }}</p>
                  <p>购买数量: {{ order.buyNum }}</p>
                  <p>订单时间: {{ order.orderTime }}</p>
                  <el-button type="success" @click="confirmPayment(order)">支付</el-button>
                  <el-button type="danger" @click="confirmHotelCancellation(order)">退订</el-button>
                </div>
                <div v-for="order in orders.hotel.upcoming" :key="order.id" class="order-item">
                  <p>订单号: {{ order.id }}</p>
                  <p>酒店ID: {{ order.hotelID }}</p>
                  <p>房间号: {{ order.roomNum }}</p>
                  <p>房间类型: {{ order.roomType }}</p>
                  <p>入住时间: {{ order.rztime }}</p>
                  <p>退房时间: {{ order.tftime }}</p>
                  <p>支付方式: {{ order.payWay }}</p>
                  <p>价格: {{ order.price }}</p>
                  <el-button type="success" @click="confirmPayment(order)">支付</el-button>
                  <el-button type="danger" @click="confirmHotelCancellation(order)">退订</el-button>
                </div>
              </div>
              <div v-else class="no-data">暂时没有相关订单</div>
            </el-tab-pane>
            <el-tab-pane label="待付款" name="pending">
              <div v-if="orders.pending.length || orders.hotel.pending.length">
                <div v-for="order in orders.pending" :key="order.id" class="order-item">
                  <p>订单号: {{ order.orderNo }}</p>
                  <p>航班ID: {{ order.flightID }}</p>
                  <p>价格: {{ order.price }}</p>
                  <p>舱位类型: {{ order.spaceType }}</p>
                  <p>总价: {{ order.tprice }}</p>
                  <p>购买数量: {{ order.buyNum }}</p>
                  <p>订单时间: {{ order.orderTime }}</p>
                  <el-button type="success" @click="confirmPayment(order)">支付</el-button>
                  <el-button type="danger" @click="confirmCancellation(order)">退订</el-button>
                </div>
                <div v-for="order in orders.hotel.pending" :key="order.id" class="order-item">
                  <p>订单号: {{ order.id }}</p>
                  <p>酒店ID: {{ order.hotelID }}</p>
                  <p>房间号: {{ order.roomNum }}</p>
                  <p>房间类型: {{ order.roomType }}</p>
                  <p>入住时间: {{ order.rztime }}</p>
                  <p>退房时间: {{ order.tftime }}</p>
                  <p>支付方式: {{ order.payWay }}</p>
                  <p>价格: {{ order.price }}</p>
                  <el-button type="success" @click="confirmPayment(order)">支付</el-button>
                  <el-button type="danger" @click="confirmCancellation(order)">退订</el-button>
                </div>
              </div>
              <div v-else class="no-data">暂时没有相关订单</div>
            </el-tab-pane>
            <el-tab-pane label="已支付" name="payed">
              <div v-if="orders.payed.length || orders.hotel.payed.length">
                <div v-for="order in orders.payed" :key="order.id" class="order-item">
                  <p>订单号: {{ order.orderNo }}</p>
                  <p>航班ID: {{ order.flightID }}</p>
                  <p>价格: {{ order.price }}</p>
                  <p>舱位类型: {{ order.spaceType }}</p>
                  <p>总价: {{ order.tprice }}</p>
                  <p>购买数量: {{ order.buyNum }}</p>
                  <p>订单时间: {{ order.orderTime }}</p>
                </div>
                <div v-for="order in orders.hotel.payed" :key="order.id" class="order-item">
                  <p>订单号: {{ order.id }}</p>
                  <p>酒店ID: {{ order.hotelID }}</p>
                  <p>房间号: {{ order.roomNum }}</p>
                  <p>房间类型: {{ order.roomType }}</p>
                  <p>入住时间: {{ order.rztime }}</p>
                  <p>退房时间: {{ order.tftime }}</p>
                  <p>支付方式: {{ order.payWay }}</p>
                  <p>价格: {{ order.price }}</p>
                </div>
              </div>
              <div v-else class="no-data">暂时没有相关订单</div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>
    <el-dialog title="确认支付" v-model="dialogVisible" width="30%" @close="resetDialog">
      <div>
        <span>确认支付订单总价为￥{{ finalPrice }}？</span>
        <el-divider></el-divider>
        <!-- 展示已选优惠券顺序 -->
        <div v-if="selectedCoupons.length > 0">
          <span>已选优惠券使用顺序：</span>
          <ul class="coupon-order-list">
            <li v-for="(coupon, index) in selectedCoupons" :key="index">
              {{ index + 1 }}. {{ coupon.name }}
            </li>
          </ul>
        </div>
        <!-- 此处修改为支持多选优惠券，使用el-checkbox-group -->
        <el-checkbox-group v-model="selectedCoupons" @change="updateSelectedCouponsAndFinalPrice">
          <el-checkbox v-for="coupon in validCoupons" :key="coupon.id" :label="coupon">
            {{ coupon.name }}
          </el-checkbox>
        </el-checkbox-group>
        <div v-if="selectedCoupons.length === 0 && coupons.length > 0">未选择优惠券</div>
      </div>
      <template v-slot:footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePayment">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="确认退订" v-model="cancelDialogVisible" width="30%" @close="resetDialog">
      <span>确认退订订单号为{{ selectedOrder.orderNo }}的订单？</span>
      <template v-slot:footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCancellation">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="确认退订" v-model="hotelCancelDialogVisible" width="30%" @close="resetDialog">
      <span>确认退订订单号为{{ selectedOrder.id }}的订单？</span>
      <template v-slot:footer>
        <el-button @click="hotelCancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleHotelCancellation">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getOrdersByUserId, updateOrder, deleteOrder } from '@/api/order';
import { getHotelOrderByUid, updateHotelOrder, deleteHotelOrder } from '@/api/hotelOrder';
import { getUserById, updateUser } from '@/api/user';
import { getCouponByUid, updateYhUser } from '@/api/coupon';

const userInfo = ref({});
const orders = ref({
  all: [],
  upcoming: [],
  pending: [],
  payed: [],
  hotel: {
    all: [],
    upcoming: [],
    pending: [],
    payed: []
  }
});
const coupons = ref([]);
const validCoupons = ref([]); // 过滤后的可用优惠券
const activeTab = ref('all');
const dialogVisible = ref(false);
const cancelDialogVisible = ref(false);
const hotelCancelDialogVisible = ref(false);
const selectedOrder = ref({});
// 此处修改为数组，用于存储选中的多张优惠券
const selectedCoupons = ref([]);
const finalPrice = ref(0);

// 获取用户ID
const userInfoString = localStorage.getItem('userInfo');
const user = ref(JSON.parse(userInfoString));
const userId = user.value.id;

// 自动更新 yhUser 表状态的方法
const updateYhUserStatus = async () => {
  try {
    // 获取用户的优惠券列表
    const couponResponse = await getCouponByUid(userId);
    if (couponResponse.code === 1) {
      const now = new Date(); // 当前时间
      const expiredCoupons = couponResponse.data.filter(coupon => new Date(coupon.term_end_time) < now);

      console.log(expiredCoupons)

      // 遍历过期的优惠券，更新 yhUser 表
      for (const coupon of expiredCoupons) {
        const yhUser = {
          id: coupon.uuid,
          status: 3 // 设置状态为 3（过期）
        };
        const updateResponse = await updateYhUser(yhUser);
        if (updateResponse.code!== 1) {
          console.error(`Failed to update yhUser for coupon ID ${coupon.id}:`, updateResponse.msg);
        }
      }
    } else {
      console.error('Failed to fetch coupons:', couponResponse.msg);
    }
  } catch (error) {
    console.error('Error updating yhUser status:', error);
  }
};

const confirmPayment = async (order) => {
  selectedOrder.value = order;
  dialogVisible.value = true;
  await loadCoupons();
  // 调用新方法获取最佳优惠券使用顺序
  selectedCoupons.value = getBestCouponOrder(validCoupons.value, selectedOrder.value);
  updateSelectedCouponsAndFinalPrice();
};

const handlePayment = async () => {
  const totalPrice = selectedOrder.value.tprice || selectedOrder.value.price;
  if (userInfo.value.money >= finalPrice.value) {
    userInfo.value.money -= finalPrice.value;
    userInfo.value.points += Math.floor(finalPrice.value / 100);

    // 更新订单状态
    selectedOrder.value.status = 'payed';
    const orderUpdateResponse = selectedOrder.value.flightID
        ? await updateOrder(selectedOrder.value)
        : await updateHotelOrder(selectedOrder.value);
    if (orderUpdateResponse.code === 1) {
      // 更新用户信息
      const userUpdateResponse = await updateUser(userInfo.value);
      if (userUpdateResponse.code === 1) {
        dialogVisible.value = false;
        await loadOrders();
      } else {
        console.error(userUpdateResponse.msg);
      }
    } else {
      console.error(orderUpdateResponse.msg);
    }
  } else {
    alert('余额不足');
  }
};

const confirmCancellation = (order) => {
  selectedOrder.value = order;
  cancelDialogVisible.value = true;
};

const handleCancellation = async () => {
  const orderDeleteResponse = await deleteOrder(selectedOrder.value.id);
  if (orderDeleteResponse.code === 1) {
    cancelDialogVisible.value = false;
    await loadOrders();
  } else {
    console.error(orderDeleteResponse.msg);
  }
};

const confirmHotelCancellation = (order) => {
  selectedOrder.value = order;
  hotelCancelDialogVisible.value = true;
};

const handleHotelCancellation = async () => {
  const orderDeleteResponse = await deleteHotelOrder(selectedOrder.value.id);
  if (orderDeleteResponse.code === 1) {
    hotelCancelDialogVisible.value = false;
    await loadOrders();
  } else {
    console.error(orderDeleteResponse.msg);
  }
};

const resetDialog = () => {
  selectedOrder.value = {};
  selectedCoupons.value = [];
  finalPrice.value = 0;
};

const loadOrders = async () => {
  const userResponse = await getUserById(userId);
  if (userResponse.code === 1) {
    userInfo.value = userResponse.data;
  } else {
    console.error(userResponse.msg);
  }

  const orderResponse = await getOrdersByUserId(userId);
  if (orderResponse.code === 1) {
    orders.value.all = orderResponse.data;
    orders.value.upcoming = orderResponse.data.filter(order => order.status === 'upcoming');
    orders.value.pending = orderResponse.data.filter(order => order.status === 'pending');
    orders.value.payed = orderResponse.data.filter(order => order.status === 'payed');
  } else {
    console.error(orderResponse.msg);
  }

  const hotelResponse = await getHotelOrderByUid(userId);
  if (hotelResponse.code === 1) {
    orders.value.hotel.all = hotelResponse.data;
    orders.value.hotel.upcoming = hotelResponse.data.filter(order => order.status === 'upcoming');
    orders.value.hotel.pending = hotelResponse.data.filter(order => order.status === 'pending');
    orders.value.hotel.payed = hotelResponse.data.filter(order => order.status === 'payed');
  } else {
    console.error(hotelResponse.msg);
  }
};

const loadCoupons = async () => {
  const couponResponse = await getCouponByUid(userId);
  if (couponResponse.code === 1) {
    // 过滤出未使用的优惠券（status === 1）
    coupons.value = couponResponse.data;
    validCoupons.value = coupons.value.filter(coupon => coupon.status === 1);
    console.log("合法优惠券：")
    console.log(coupons.value)
  } else {
    console.error(couponResponse.msg);
  }
  // 在页面加载时更新用户信息
  await loadUserInfo();
};

const loadUserInfo = async () => {
  const userResponse = await getUserById(userId);
  if (userResponse.code === 1) {
    userInfo.value = userResponse.data;
  } else {
    console.error(userResponse.msg);
  }
};

// 用于更新选中优惠券及最终价格，并处理队列显示相关逻辑
const updateSelectedCouponsAndFinalPrice = () => {
  updateFinalPrice();
};

const updateFinalPrice = () => {
  const totalPrice = selectedOrder.value.tprice || selectedOrder.value.price;
  let tempPrice = totalPrice;
  // 循环遍历选中的优惠券，按照顺序计算最终价格
  for (const coupon of selectedCoupons.value) {
    const { discount_type, discount_value, threshold_amount } = coupon;
    if (threshold_amount > tempPrice) {
      continue;
    }
    if (discount_type === 1) {
      const times = Math.floor(tempPrice / threshold_amount);
      tempPrice = tempPrice - times * discount_value;
    } else if (discount_type === 2) {
      tempPrice = tempPrice * (discount_value / 10);
    } else if (discount_type === 3) {
      tempPrice = tempPrice - discount_value;
    }
  }
  finalPrice.value = tempPrice;
};

const isCouponValid = (coupon) => {
  const totalPrice = selectedOrder.value.tprice || selectedOrder.value.price;
  return totalPrice >= coupon.threshold_amount;
};

const removeSelectedCoupon = (index) => {
  selectedCoupons.value.splice(index, 1);
  updateFinalPrice();
};

// 新增方法用于获取最佳优惠券使用顺序
const getBestCouponOrder = (coupons, order) => {
  const totalPrice = order.tprice || order.price;
  let bestCombination = [];
  let bestDiscount = 0;
  let minCouponCount = Infinity;
  // 生成所有可能的优惠券组合
  const generateCombinations = (arr, n) => {
    if (n === 0) {
      return [[]];
    }
    if (arr.length === 0) {
      return [];
    }
    const result = [];
    const withoutFirst = generateCombinations(arr.slice(1), n);
    result.push(...withoutFirst);
    const withFirst = generateCombinations(arr.slice(1), n - 1).map(comb => [arr[0],...comb]);
    result.push(...withFirst);
    return result;
  };
  // 遍历所有组合，找到最佳的优惠券使用顺序
  for (let numCoupons = 1; numCoupons <= coupons.length; numCoupons++) {
    const combinations = generateCombinations(coupons, numCoupons);
    for (const combination of combinations) {
      let tempPrice = totalPrice;
      let currentDiscount = 0;
      let isValidCombination = true;
      const sortedCombination = combination.slice().sort((a, b) => {
        if (a.discount_type === b.discount_type) {
          return b.discount_value - a.discount_value;
        }
        return a.discount_type - b.discount_type;
      });
      for (const coupon of sortedCombination) {
        const { discount_type, discount_value, threshold_amount } = coupon;
        if (threshold_amount > tempPrice) {
          isValidCombination = false;
          break;
        }
        if (discount_type === 1) {
          const times = Math.floor(tempPrice / threshold_amount);
          currentDiscount += times * discount_value;
          tempPrice = tempPrice - times * discount_value;
        } else if (discount_type === 2) {
          currentDiscount += tempPrice * (1 - discount_value / 10);
          tempPrice = tempPrice * (discount_value / 10);
        } else if (discount_type === 3) {
          currentDiscount += discount_value;
          tempPrice = tempPrice - discount_value;
        }
      }
      if (isValidCombination && (currentDiscount > bestDiscount || (currentDiscount === bestDiscount && combination.length < minCouponCount))) {
        bestDiscount = currentDiscount;
        bestCombination = sortedCombination;
        minCouponCount = combination.length;
      }
    }
  }
  return bestCombination;
};

onMounted(async () => {
  await updateYhUserStatus(); // 自动更新yhUser表状态
  await loadOrders();
  await loadCoupons(); // 页面加载时加载优惠券信息
});
</script>

<style scoped>
.profile-main {
  height: 90vh;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9f9f9;
}

.profile-summary {
  padding: 10px 0;
}

.order-status {
  padding: 20px 0;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #888;
}

.order-item {
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
  margin-bottom: 10px;
}

.el-card {
  margin-bottom: 20px;
}

.el-button {
  margin-top: 10px;
}

/* 优化确认支付对话框中优惠券顺序列表的样式 */
.coupon-order-list {
  list-style-type: none;
  padding: 0;
  margin: 10px 0;
}

.coupon-order-list li {
  padding: 5px 0;
  border-bottom: 1px solid #ccc;
}
</style>